package com.jspgou.cms.action.front;

import static com.jspgou.cms.Constants.SHOP_SYS;
import static com.jspgou.cms.Constants.TPLDIR_PRODUCT;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.jspgou.common.web.ResponseUtils;
import com.jspgou.common.web.springmvc.MessageResolver;
import com.jspgou.core.entity.ShopDictionary;
import com.jspgou.core.entity.Website;
import com.jspgou.core.manager.MemberMng;
import com.jspgou.core.manager.ShopDictionaryMng;
import com.jspgou.cms.entity.Consult;
import com.jspgou.cms.entity.Discuss;
import com.jspgou.cms.entity.OrderItem;
import com.jspgou.cms.entity.Product;
import com.jspgou.cms.entity.ShopMember;
import com.jspgou.cms.entity.Store;
import com.jspgou.cms.manager.ConsultMng;
import com.jspgou.cms.manager.DiscussMng;
import com.jspgou.cms.manager.OrderItemMng;
import com.jspgou.cms.manager.ProductMng;
import com.jspgou.cms.web.CmsUtils;
import com.jspgou.cms.web.ShopFrontHelper;
import com.jspgou.cms.web.SiteUtils;

@Controller
public class ProductFormAct {
	private static final Logger log = LoggerFactory.getLogger(ProductFormAct.class);
	
	/**
	 * 商品页中评价列表页(分页)
	 */
	private static final String TPL_PRODUCT_DISSCUSS="tpl.productDiscuss";
	/**
	 * 商品页中咨询列表页(分页)
	 */
	private static final String TPL_PRODUCT_CONSULT="tpl.productConsult";
	/**
	 * 购买记录列表页(分页)
	 */
	private static final String TPL_PRODUCT_BARGAIN="tpl.bargain";
	
	// 查询 买家评论(分页)
	@RequestMapping(value = "/searchDiscussPage*.jspx")
	public String searchDiscussPage(Long productId,HttpServletResponse response,
			HttpServletRequest request, ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		
		//从数据字典中查询咨询类型，将咨询类型传递到前台
		List<ShopDictionary> discussTypes=dictionaryMng.getList("discussType");
        model.addAttribute("discussTypes", discussTypes);
		model.addAttribute("product", productMng.findById(productId));
		ShopFrontHelper.setCommonData(request, model, web);
		ShopFrontHelper.frontPageData(request, model);
		return web.getTemplate(TPLDIR_PRODUCT, MessageResolver.getMessage(request,
				TPL_PRODUCT_DISSCUSS), request);
	}
	
	// 查询 购买咨询(分页)
	@RequestMapping(value = "/consultProduct*.jspx")
	public String consultProduct(Long productId,HttpServletResponse response, 
			HttpServletRequest request,ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		//东哥更改
		List<ShopDictionary> consultTypes = dictionaryMng.getList("consultType");
		Product bean = productMng.findById(productId);
		model.addAttribute("product", bean);
		model.addAttribute("consultTypes", consultTypes);
		ShopFrontHelper.setCommonData(request, model, web);
		ShopFrontHelper.frontPageData(request, model);
		return web.getTemplate(TPLDIR_PRODUCT, MessageResolver.getMessage(request,
				TPL_PRODUCT_CONSULT), request);
	}

	// 插入咨询,添加字段consultType，用于生成咨询类型
	@RequestMapping(value = "/insertConsult.jspx")
	public void insertConsult(Long productId, Long storeId,
			String content,String consultType,HttpServletResponse response, 
			HttpServletRequest request,ModelMap model) {
		ShopMember member=CmsUtils.getMember(request);
		if (member == null) {
			ResponseUtils.renderJson(response, "false");
		}
		Consult bean = consultMng.saveOrUpdate(productId,storeId,content,consultType,member.getId());
		if (bean == null) {
			ResponseUtils.renderJson(response, "sameUsually");
		}
		ResponseUtils.renderJson(response, "success");
	}

	@RequestMapping(value = "/getStores.jspx", method = RequestMethod.POST)
	public String addToCart(Long productId, Long fashId,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap model) {
		ShopMember member=CmsUtils.getMember(request);
		Integer store = productMng.getStoreByProductPattern(productId, fashId);
		ResponseUtils.renderJson(response, store + "");
		return null;
	}

	@RequestMapping(value = "/getTotalStore.jspx", method = RequestMethod.POST)
	public String getTotalStore(Long productId, HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		Integer store = productMng.getTotalStore(productId);
		ResponseUtils.renderJson(response, store + "");
		return null;
	}
	
	
	//确认用户是否购买该商品，没有则无权利评论
	@RequestMapping(value = "/haveDiscuss.jspx")
	public String haveDiscuss(HttpServletRequest request,
			HttpServletResponse response, Long productId,ModelMap model) {
		ShopMember member=CmsUtils.getMember(request);
		if (member == null) {
			ResponseUtils.renderJson(response, "denru");
			return null;
		}
		if(discussMng.getList(member.getId(), productId).size()>0){
			/*
			 * 为了实现用户更改评论功能，先判定该用户是否对该商品评论过。
			 * 如果评论过，则将用户评论传递到前台，同时，也说明用户购买过该商品。
			 * 将成员也传递给前台
			 */
			ResponseUtils.renderJson(response, "updateDiscuss");
			return null;
		}
		OrderItem bean = orderItemMng.findByMember(member.getId(), productId);
		/*
		 * 注解，程序利用该用户是否拥有该商品的订单项，
		 * 来判断该用户是否购买过该商品，有些不妥，应该是在订单类中有类似描述订单状态的字段。
		 * 比如，未购买；购买未付款；付款未发货；已发货但未确认收货；买家确认收货交易顺利完成,
		 * 当订单状态为交易顺利完成时，用户才有资格对商品进行评论
		 */
		if (bean != null) {
			ResponseUtils.renderJson(response, "success");
			return null;
		} else {
			ResponseUtils.renderJson(response, "false");
			return null;
		}	
	}
	
	// 插入或者更改买家评论
	@RequestMapping(value = "/saveOrUpdateDiscuss.jspx")
	public String saveOrUpdateDiscuss(Long productId,Long storeId, String disContent,String discussType,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap model) {
		ShopMember member=CmsUtils.getMember(request);
		if (member == null) {
			ResponseUtils.renderJson(response, "false");
			return null;
		}
		OrderItem orderItem = orderItemMng.findByMember(member.getId(), productId);
		/*
		 * 根据用户id和商品id查询数据库中对应的discuss，如果不存在，则保存discuss，如果存在，则更改discuss
		 */
		if(discussMng .getList(member.getId(), productId).size()>0){
			Discuss bean=discussMng.getList(member.getId(), productId).get(0);
			bean.setContent(disContent);
			bean.setDiscussType(discussType);
			bean.setTime(new Date());
			discussMng.save(bean);
			ResponseUtils.renderJson(response, "updateSuccess");
			return null;
		}
		discussMng.saveOrUpdate(productId, disContent, member.getId(),storeId,orderItem.getId(), discussType);
		ResponseUtils.renderJson(response, "success");
		return null;
	}
	// 查询成交记录(分页)
		@RequestMapping(value = "/bargain*.jspx")
		public String bargain(Integer pageNo, Long productId,
				HttpServletResponse response, HttpServletRequest request,
				ModelMap model) {
			Website web = SiteUtils.getWeb(request);
			Product bean = productMng.findById(productId);
			model.addAttribute("product", bean);
			ShopFrontHelper.setCommonData(request, model, web);
			ShopFrontHelper.frontPageData(request, model);
			return web.getTemplate(SHOP_SYS, MessageResolver.getMessage(request,TPL_PRODUCT_BARGAIN), request);
		}

	
	// 会员浏览历史记录
	@RequestMapping(value = "/historyRecord.jspx")
	public String historyRecord(Long productId, HttpServletResponse response,
			HttpServletRequest request) {
		ShopMember member=CmsUtils.getMember(request);
		if (member == null) {
			return null;
		}
		String str = "";
		Cookie[] cookeis = request.getCookies();
		for (int i = 0; i < cookeis.length; i++) {
			if (cookeis[i].getName().equals("shop_record")) {
				str = "," + cookeis[i].getValue();
				break;
			}
		}
		str = productId + str;
		
		int n = 0, m = 0;
		for (int i = 0; i < str.length(); i++) {
			if (str.charAt(i) == ',') {
				n++;
			}
			if (n == 6) {
				break;
			}
			m = i + 1;
		}
		Cookie cook = new Cookie("shop_record", str.substring(0,m));
		String path = request.getContextPath();
		cook.setPath(StringUtils.isBlank(path) ? "/" : path);
		response.addCookie(cook);
		return null;
	}

	@Autowired
	private ProductMng productMng;
	@Autowired
	private ConsultMng consultMng;
	@Autowired
	private OrderItemMng orderItemMng;
	@Autowired
	private DiscussMng discussMng;
	@Autowired
	private ShopDictionaryMng dictionaryMng;
	@Autowired
	private MemberMng memberMng;
}
